<template>
  <el-row>
    <el-col :span="spanRow">
      <div class="search">
        <el-form :inline="true"
                 class="demo-form-inline"
                 @submit.native.prevent>
          <el-form-item label="城市">
            <el-input v-model="address"
                      placeholder="城市"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <el-table ref="table"
                v-loading="loading"
                element-loading-text="加载中"
                element-loading-spinner="el-icon-loading"
                :data="tableData.filter(data => !address || (data.fromCity + data.toCity).includes(address))"
                class="table-box"
                max-height="500px"
                :row-class-name="tableRowClassName"
                :row-key="record => record.id"
                border>
        <template v-for="(item, index) in tableColumn">
          <Address :key="index"
                   :item="item"
                   :index="index" />
        </template>
        <el-table-column v-if="hidden"
                         align="center"
                         label="操作"
                         width="120">
          <template slot-scope="scope">
            <div v-if="separateBarga">
              <el-button v-if="scope.row.bargain"
                         type="text"
                         size="small"
                         @click="merge(scope.$index, scope.row)">采纳</el-button>
              <el-button v-if="scope.row.edit"
                         type="text"
                         size="small"
                         @click="bargainEdit(scope.$index, scope.row)">编辑</el-button>
            </div>
            <div v-else>
              <el-button v-if="!rejectedStatus && bargaStatus && !scope.row.locaBargain"
                         type="text"
                         size="small"
                         @click="bargain(scope.$index, scope.row)">议价</el-button>
              <el-button v-if="rejectedStatus || !bargaStatus || scope.row.edit"
                         type="text"
                         size="small"
                         @click="edit(scope.$index, scope.row)">{{ '编辑' }}</el-button>
              <el-button v-if="rejectedStatus || !bargaStatus || scope.row.locaBargain"
                         type="text"
                         size="small"
                         @click="clear(scope.$index, scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <!-- <el-pagination :current-page="currentPage"
                     align='right'
                     :page-sizes="[10,20, 30, 50]"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="tableData.length"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange">
      </el-pagination> -->
    </el-col>
    <el-col v-if="valueObject"
            :span="8">
      <AddVehicleForm ref="vehicleForm"
                      :value="row"
                      :edit-status="editStatus"
                      :barga-status="bargaStatus"
                      @add="addRow" />
    </el-col>
  </el-row>
</template>

<script>
import AddVehicleForm from './components/AddVehicleForm.vue'
import Address from './components/Address.vue'
// import vehicleModel from "@basic/assets/vehicle.models";
import {
  render, reducePrice, model,
  EditableIncludes,
  hasSameSingleTemplateRuleId,
  detailAddressAssignment,
  isExistingVehicleItem,
  confirmExistingData,
} from '../index'
import eventBus from "@/libs/eventBus";
import { mapActions } from "vuex";
import { v4 } from 'uuid'

export default {
  name: 'Vehicle',
  components: { AddVehicleForm, Address },
  props: {
    specs: {
      type: Object,
      default: () => { }
    },
    valueObject: {
      type: Boolean,
      default: false
    },
    spanRow: {
      type: [String, Number],
      default: 16
    },
    bargaStatus: {
      type: [String, Number],
      default: null
    },
    response: {
      type: Boolean,
      default: false
    },
    importStatus: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      input: '',
      editStatus: null,
      // loading: false,
      tableColumn: [
        {
          prop: 'fromCity',
          label: '起点城市',
          isFromAddress: true
        },
        {
          prop: 'toCity',
          label: '目的城市',
          isToAddress: true
        },
        {
          prop: 'vehicleModelDesc',
          label: '车型',
          isVehicleModelDesc: true
        },
        {
          prop: 'vehicleLengthDesc',
          label: '车辆信息',
          width: '180',
          isVehicleLengthDesc: true
        },
        {
          prop: 'price',
          label: '价格（元）',
          isPrices: true
        },
        {
          prop: 'days',
          label: '时效（天）'
        }
      ],
      loading: false,
      isTip: false,
      tableData: [],
      selectedArrData: [],
      row: {},
      pageSize: 10,
      currentPage: 1,
      address: '',
      separateBarga: null,
      bargainIds: null,
      areaOptions: []
    }
  },
  computed: {
    // loading () {
    //   return this.response ? false : true
    // },
    query () {
      return this.$route.query
    },
    detail () {
      return this.specs?.detailData
    },
    // showDelete () {
    //   return this.detail?.status ? true : false
    // },
    initStatus () {
      return this.query.status || this.query.templateId
    },
    hidden () {
      return this.isShowDelete || !this.query.templateId
    },
    /* 被拒绝状态 */
    rejectedStatus () {
      return Number(this.bargaStatus) === 3
    },
    isShowDelete () {
      let haveStatus = null
      // if (this.detail?.status != 11 || this.detail?.status != 14) {
      if (EditableIncludes().includes(this.detail?.status)) {
        haveStatus = true
      } else {
        haveStatus = false
      }
      return haveStatus
    },
    vehicleLengthDesc () {
      return ({ args }) => {
        let desc = null
        let label = args?.pressLoadLabel || '米'
        if (args.vehicleLength === 999) {
          desc = `其它 / ${args?.vehicleVolume || ''}立方米 / ${args?.vehicleWeight || ''}吨`
        } else {
          desc = `${args.vehicleLength || ''}${label} / ${args?.vehicleVolume || ''}立方米 / ${args?.vehicleWeight || ''}吨`
        }
        return desc
      }
    },
    wholes () {
      return this.specs?.whole
    },
    whole () {
      return ({ whole }) => {
        // this.separateBarga = whole.some(item => item.bargain)
        if (this.bargainIds || (Number(this.query.status) === 8 && this.query.templateId)) {
          const bargainList = whole.filter(item => item.bargain)
          if (bargainList) {
            this.separateBarga = true
          } else {
            this.separateBarga = false
          }
        }
        for (let i = 0; i < whole.length; i++) {
          if (whole[i].bargain) {
            const index = i - 1;
            whole[index].edit = true
          }
        }
        return whole.map((item) => {
          const { fromAddress, toAddress, vehicleModel, ...surplus } = item
          const transformModel = model({ model: vehicleModel })
          return {
            ...surplus,
            ...render({ props: fromAddress, key: 'fromAddress', name: 'fromCity', pos: 'startCity' }),
            ...render({ props: toAddress, key: 'toAddress', name: 'toCity', pos: 'endCity' }),
            vehicleModelDesc: transformModel?.name,
            vehicleModel: transformModel?.value,
            vehicleLengthDesc: this.vehicleLengthDesc({ args: surplus }),
            code: v4()
          }
        })
      }
    },
    // checkAddressWhole () {
    //   return whole => {
    //     const wholes = checkAddressErrors(JSON.parse(JSON.stringify(whole)), this.areaOptions)
    //     return wholes
    //   }
    // },
    init () {
      return this.whole({ whole: this.wholes })
    }
    // tableData () {
    //   return this.loading ? [] : this.whole({ whole: this.specs?.whole })
    // }
  },
  watch: {
    'query.templateId': function (vlaue) {
      this.bargainIds = vlaue
    },
    response () {
      this.tableData = this.initStatus || this.importStatus ? this.init : [];
    }
  },
  async created () {
    this.tableData = this.initStatus || this.importStatus ? this.init : [];
    // this.tableData = this.query ? this.whole({ whole: this.specs?.whole }) : [];
  },
  mounted () {
    eventBus.$off("clearBargaData");
    eventBus.$on("clearBargaData", () => {
      this.tableData = this.tableData.filter(items => !items.locaBargain)
      this.tableColumn = this.tableColumn.filter(item => item.prop !== 'remarks')
    });
  },
  methods: {
    ...mapActions({
      buffWhole: "quotation/buffWhole",
      buffbargaWhole: "quotation/buffbargaWhole"
    }),
    tableRowClassName ({ row }) {
      if (row?.bargain || row?.locaBargain) {
        return 'warning-row'
      }
      //  else if (row?.isFromError || row?.isToError) {
      //   return 'row-style'
      // }
      return
    },
    //pageSize改变时触发的事件
    // handleSizeChange (val) {
    //   console.log(`每页 ${val} 条`);
    //   this.currentPage = 1; //始终保持第一页
    //   this.pageSize = val; //将改变的值赋给pageSize
    // },
    //当前页码发生改变时触发的事件
    // handleCurrentChange (val) {
    //   console.log(`当前页: ${val}`);
    //   this.currentPage = val; //改变当前页码
    // },
    edit (index, row) {
      if (row?.isFromError) {
        row.startCity = []
      }
      if (row?.isToError) {
        row.endCity = []
      }
      const rows = Object.assign({}, row)
      const fromAddress = row.fromAddress?.address
      const toAddress = row.toAddress?.address
      // this.selectedArrData = [rows]
      if (typeof row.vehicleModel !== 'object') {
        rows.vehicleModel = model({ model: rows.vehicleModel })
        rows.vehicleOptions = rows?.vehicleModel?.length
      }
      this.row = { row: { ...rows, edit: true, index: index, startAddress: fromAddress, endAddress: toAddress } }
      this.editStatus = true
    },

    bargainEdit (index, row) {
      const rows = Object.assign({}, row)
      const fromAddress = row.fromAddress?.address
      const toAddress = row.toAddress?.address
      if (typeof row.vehicleModel !== 'object') {
        rows.vehicleModel = model({ model: rows.vehicleModel })
        rows.vehicleOptions = rows.vehicleModel.length
      }
      this.row = { row: { ...rows, edit: true, index: index, startAddress: fromAddress, endAddress: toAddress } }
      console.log('议价过后', this.row)
      this.bargainLaterStatus = true
      // this.editStatus = true
    },

    merge (index, row) {
      const rows = Object.assign({}, row)
      rows.bargain = false
      /* 问下产品看是否能再次编辑 */
      rows.edit = true
      this.tableData[index - 1] = rows
      this.tableData.splice(index, 1)
      this.buffWhole({ data: JSON.parse(JSON.stringify(this.tableData)) })
    },
    clear (index) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData.splice(index, 1)
        this.buffWhole({ data: JSON.parse(JSON.stringify(this.tableData)) })
      })
    },
    bargain (index, row) {
      const rows = Object.assign({}, row)
      const fromAddress = row.fromAddress?.address
      const toAddress = row.toAddress?.address
      // this.selectedArrData = [rows]
      if (typeof row.vehicleModel !== 'object') {
        rows.vehicleModel = model({ model: rows.vehicleModel })
      }
      if (hasSameSingleTemplateRuleId(this.tableData)) {
        this.row = { row: { ...rows, edit: true, index: index, startAddress: fromAddress, endAddress: toAddress } }
        this.editStatus = true
        return
      }
      this.row = { row: { ...rows, locaBargain: true, index: index, startAddress: fromAddress, endAddress: toAddress } }
    },
    addRow (item) {
      const bargaTableData = []
      // let mergedTableData = []
      this.isTip = false
      const { fromAddress, toAddress, vehicleModel, ...args } = item
      if (args?.startAddress) {
        fromAddress.address = args?.startAddress
      }
      if (args?.endAddress) {
        toAddress.address = args?.endAddress
      }
      const filterColumn = this.tableColumn.filter(item => item.prop === 'remarks')
      const row = {
        vehicleModel: vehicleModel.value,
        vehicleModelDesc: vehicleModel.name,
        // vehicleLengthDesc: this.vehicleLengthDesc({ args: args }),
        ...args,
        ...render({ props: fromAddress, key: 'fromAddress', name: 'fromCity', pos: 'startCity' }),
        ...render({ props: toAddress, key: 'toAddress', name: 'toCity', pos: 'endCity' }),
        code: v4()
      }
      let rows = Object.assign({}, row)

      if (this.bargaStatus && this.editStatus && this.bargaStatus !== 3) {
        /* 已经存在议价上游数据状态 */
        if (!filterColumn.length) {
          this.tableColumn = [...this.tableColumn, { prop: 'remarks', label: '备注' }]
        }
        this.editStatus = false
        const currentData = this.tableData[item.index]
        const nextData = this.tableData[item.index + 1]

        if (rows?.templateRuleId === currentData?.templateRuleId && nextData?.locaBargain) {
          this.tableData.splice(item.index + 1, 1, { ...rows, locaBargain: true, edit: false })
        } else {
          this.tableData.splice(item.index + 1, 0, { ...rows, locaBargain: true, edit: false })
        }
        this.$message.success('操作成功')
        // this.tableData.splice(item.index + 1, 1, { ...rows, locaBargain: true, edit: false })
        // this.tableData = reduce({ data: this.tableData, rows: [rows] })

      } else if (this.bargaStatus && this.bargainLaterStatus) {
        // 已存在议价下游数据详情
        const transformRows = detailAddressAssignment({ rows: JSON.parse(JSON.stringify(rows)) })
        this.tableData.splice(item.index, 1, { ...transformRows })
        this.tableData.splice(item.index + 1, 1)
        // mergedTableData.push(...this.tableData)
        this.$message.success('操作成功')

      } else if (this.bargaStatus && this.bargaStatus !== 3) {

        if (!filterColumn.length) {
          this.tableColumn = [...this.tableColumn, { prop: 'remarks', label: '备注' }]
        }
        const tableDataIndex = this.tableData[item.index]
        const nextData = this.tableData[item.index + 1]

        const isReduePrice = reducePrice({ data: tableDataIndex, rows: rows })
        if (isReduePrice) {
          if (rows?.templateRuleId === tableDataIndex?.templateRuleId && nextData?.locaBargain) {
            this.tableData.splice(item.index + 1, 1, { ...rows, locaBargain: true, edit: false })
          } else {
            this.tableData.splice(item.index + 1, 0, { ...rows, locaBargain: true, edit: false })
          }
          // this.tableData.splice(item.index + 1, 0, isReduePrice)
        }
      } else if (this.editStatus) {

        this.editStatus = false
        const importedValidation = this.validateRows(rows)

        /* 导入数据编辑 */
        if (!importedValidation) {
          Object.keys(rows).forEach(key => {
            if (key.startsWith('is')) {
              delete rows[key]
            }
          })
          // this.tableData.splice(item.index, 1);
        }
        this.isTip = true
        const transformRows = detailAddressAssignment({ rows: JSON.parse(JSON.stringify(rows)) })
        const vehicleLengthDesc = this.vehicleLengthDesc({ args: args })
        // this.tableData.splice(item.index, 1, { ...transformRows, vehicleModelDesc: vehicleModel.name, vehicleLengthDesc, edit: false })

        // const existingItem = isExistingVehicleItem({ tableData: this.tableData, transformRows: transformRows })
        // console.log('整车重复数据编辑existingItem', existingItem)
        // if (existingItem) {
        //   confirmExistingData().then(res => {
        //     console.log('整车重复数据编辑', res)
        //     this.tableData.forEach((item, index) => {

        //       if (item.fromCity === transformRows?.fromCity
        //         && item.toCity === transformRows?.toCity
        //         && item.vehicleModel === transformRows?.vehicleModel
        //         && item.vehicleLength === transformRows?.vehicleLength) {
        //         if (item.fromAddress.address && item.fromAddress.address !== undefined || item.toAddress.address && item.toAddress.address !== undefined) {
        //           if (item.fromAddress.address === transformRows?.fromAddress?.address && item.toAddress.address === transformRows?.toAddress?.address) {
        //             this.tableData.splice(index, 1, { ...transformRows, vehicleModelDesc: vehicleModel.name, vehicleLengthDesc, edit: false })
        //             return
        //           }
        //           return
        //         }
        //         this.tableData.splice(index, 1, { ...transformRows, vehicleModelDesc: vehicleModel.name, vehicleLengthDesc, edit: false })
        //       }
        //     })
        //   })
        // } else {
        //   const index = this.tableData.findIndex(item => item.locaBargain)
        //   if (index !== -1) {
        //     this.tableData.splice(index + 1, 0, { ...transformRows, vehicleModelDesc: vehicleModel.name, vehicleLengthDesc, locaBargain: true, edit: false })
        //   } else {
        //     this.tableData.unshift({ ...transformRows, vehicleModelDesc: vehicleModel.name, vehicleLengthDesc })
        //   }
        // }
        this.tableData.splice(item.index, 1, { ...transformRows, vehicleModelDesc: vehicleModel.name, vehicleLengthDesc, edit: false })
        this.$message.success('操作成功')
      } else {
        // 添加数据
        const transformRows = detailAddressAssignment({ rows: JSON.parse(JSON.stringify(rows)) })
        const vehicleLengthDesc = this.vehicleLengthDesc({ args: args })

        if (!this.tableData.length) {
          this.tableData.unshift({ ...transformRows, vehicleModelDesc: vehicleModel.name, vehicleLengthDesc })
          this.buffWhole({ data: JSON.parse(JSON.stringify(this.tableData)) })
          return
        }
        // 添加数据
        const importedValidation = this.validateRows(transformRows)
        /* 导入数据新增 */
        if (!importedValidation) {
          Object.keys(transformRows).forEach(key => {
            if (key.startsWith('is')) {
              delete transformRows[key]
            }
          })
          this.tableData.splice(item.index, 1);
        }
        this.isTip = true
        const existingItem = isExistingVehicleItem({ tableData: this.tableData, transformRows: transformRows })
        console.log('整车重复数据新增existingItem', existingItem)
        if (existingItem) {
          confirmExistingData().then(res => {
            console.log('整车重复数据新增', res)
            this.tableData.forEach((item, index) => {
              if (item.fromAddress?.address && transformRows.fromAddress?.address && item.fromAddress.address === transformRows?.fromAddress?.address
                || item.toAddress?.address && transformRows.toAddress?.address && item.toAddress.address === transformRows?.toAddress?.address
              ) {
                this.tableData.splice(index, 1, { ...transformRows, vehicleModelDesc: vehicleModel.name, vehicleLengthDesc, edit: false })
              }
              if (item.fromCity === transformRows?.fromCity
                && item.toCity === transformRows?.toCity
                && item.vehicleModel === transformRows?.vehicleModel
                && item.vehicleLength === transformRows?.vehicleLength
                // && item.billingUnit === transformRows?.billingUnit
              ) {
                this.tableData.splice(index, 1, { ...transformRows, vehicleModelDesc: vehicleModel.name, vehicleLengthDesc, edit: false })
              }
            })
          })
        } else {
          // 添加数据
          const importedValidation = this.validateRows(transformRows)
          /* 导入数据新增 */
          if (!importedValidation) {
            Object.keys(transformRows).forEach(key => {
              if (key.startsWith('is')) {
                delete transformRows[key]
              }
            })
            this.tableData.splice(item.index, 1);
          }
          const index = this.tableData.findIndex(item => item.locaBargain)
          if (index !== -1) {
            this.tableData.splice(index + 1, 0, { ...transformRows, vehicleModelDesc: vehicleModel.name, vehicleLengthDesc, locaBargain: true, edit: false })
          } else {
            this.tableData.unshift({ ...transformRows, vehicleModelDesc: vehicleModel.name, vehicleLengthDesc })
          }
          // return this.tableData.unshift({ ...transformRows, vehicleModelDesc: vehicleModel.name, vehicleLengthDesc })
        }

      }
      const bargaData = this.tableData.filter(item => item?.locaBargain)
      bargaTableData.push(...bargaData)

      this.buffbargaWhole({ data: JSON.parse(JSON.stringify(bargaTableData)) })
      this.buffWhole({ data: JSON.parse(JSON.stringify(this.tableData)) })
      if (!this.isTip) {
        this.$message.success('操作成功')
      }
    },
    validateRows (rows) {
      const { isDaysError, isFromError, isToError, isVehicleModelError, isVehicleLengthError, isPriceError } = rows;
      return !(isDaysError || isFromError || isToError || isVehicleModelError || isVehicleLengthError || isPriceError);
    }
    // uniqueArray ({ array }) {
    //   return array.filter((item, index, arr) => {
    //     return arr.findIndex(itemInner => (
    //       itemInner.fromCity === item.fromCity
    //       && itemInner.toCity === item.toCity
    //       && itemInner.vehicleModel === item.vehicleModel
    //       && itemInner.vehicleLength === item.vehicleLength
    //       && itemInner.fromAddress.address === item.fromAddress.address
    //       && itemInner.toAddress.address === item.toAddress.address
    //     )) === index;
    //   })
    // }
  }
}
</script>

<style scoped>
.el-pagination {
  padding: 8px 5px !important;
}
::v-deep.table-box .warning-row td {
  color: rgb(98 189 255);
  background: #f8ecda !important;
  color: var(--prev-color-text-purered);
}
</style>
<style lang="scss" scoped>
.search /deep/ .el-input--prefix {
  width: 200px;
}
.table-box {
  width: 99.9% !important;
}
</style>